package com.zys.sac.starter.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

/**
 * @author junekzhong
 * @date 2023/12/13 15:36
 */
@Slf4j
public class ConditionalOnAnyPropertyMatcher implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionalOnAnyProperty.class.getName());
        String prefix = (String) annotationAttributes.get("prefix");
        String[] propertyNames = (String[]) annotationAttributes.get("name");
        String havingValue = (String) annotationAttributes.get("havingValue");
//        // 如果没有指定该属性或者该属性没有值，就使用这个默认值
        boolean matchIfMissing = (Boolean) annotationAttributes.get("matchIfMissing");
        String propertyValue = "";
        for (String propertyName : propertyNames) {
            propertyName = prefix + "." + propertyName;
            propertyValue = context.getEnvironment().getProperty(propertyName);
            // 如果配置文件设置了该参数，并且值与havingValue属性一致，返回true
            if (StrUtil.isNotBlank(propertyValue) && propertyValue.equals(havingValue)) {
                 return true;
            }
        }
        // 说明有值，并且该值与havingValue的属性不一致
        if (StrUtil.isNotBlank(propertyValue)) {
            return false;
        }
        // 如果没有设置值，则使用默认值
        return matchIfMissing;
    }
}
